package BookManager;


import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//第七页，通过这个类给数据库的连接操作进行封装。

public class DBUtil {
    private static String url="jdbc:mysql://127.0.0.1:3306/library?serverTimezone=GMT&allowPublicKeyRetrieval=true&useSSL=false&characterEncoding=utf8";
    private static String username="zhang";
    private static String password="xijie9401";

    private static DataSource dataSource=new MysqlDataSource();

    //静态代码块，在类加载时就运行
    static {
        ((MysqlDataSource)dataSource).setURL(url);
        ((MysqlDataSource)dataSource).setUser(username);
        ((MysqlDataSource)dataSource).setPassword(password);
    }

    //创建一个方法，建立连接。
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    //创建一个释放方法
    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement!= null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
